


var rongcloudSDK = require('rongcloud-sdk');
var mongoose = require('mongoose');
var config = require("../dict/config")
var yz = require("../../models/comm/yz")
var mongo = require("../mongo/mongo");
var superagent = require('superagent');
var sha1 = require('sha1');
var BASEURL = 'https://api.cn.rong.io';


rongcloudSDK.init(config.rongAppKey, config.rongAppSecret);




exports.getToken = function (member) {





    return new Promise((resolve, reject) => {
        rongcloudSDK.user.getToken(member._id.toString(), "", "", function (err, resultText) {
            if (err) {
                // Handle the error


                reject(err)
            }
            else {
                var result = JSON.parse(resultText);
                if (result.code === 200) {
                    //Handle the result.token


                }
                console.dir(result);
                resolve(result)

            }
        });
    });


};


exports.sendMsg = async function (msg, o) {
    // body...






    msg = yz.IsNullThen(msg, {})

    o = yz.IsNullThen(o, {})
    msg.formUserId = yz.IsNullThen(msg.formUserId, "messager")
    msg.extra = yz.IsNullThen(msg.extra, {})

    msg.content = yz.IsNullThen(msg.content, "")
    if (!msg.pushContent) {
        msg.pushContent = ""
    }
    if (o.noLog) {
        //不记录,只提醒
    }
    else {
        var re = await mongo.SaveAsync({

            data: msg,
            collection: "msgPush"
        })
    }




    return await send(msg)



};


async function send(msg) {


    return new Promise(async (resolve, reject) => {

        var content = {
            content: msg.content,
            extra: msg.extra
        }
        var toUserId = msg.toUserId




        APPKEY = config.rongAppKey;
        APPSECRET = config.rongAppSecret;
        NONCE = parseInt(Math.random() * 0xffffff);
        TIMESTAMP = Date.parse(new Date()) / 1000;
        SIGNATURE = sha1(APPSECRET + NONCE + TIMESTAMP);
        var HEADERS = {};
        HEADERS['App-Key'] = APPKEY;
        HEADERS['Nonce'] = NONCE;
        HEADERS['Timestamp'] = TIMESTAMP;
        HEADERS['Signature'] = SIGNATURE;

        HEADERS['Content-Type'] = 'application/x-www-form-urlencoded';

        var f = 'json';

        var toUserId = ""
        if (yz.isArray(msg.toUserId)) {
            //如果是群发数组
            if (msg.toUserId.length == 0) {
                resolve();
            }


            var w = [];
            msg.toUserId.forEach(function (element) {
                w.push("&toUserId=" + element + "")
            }, this);

            toUserId = w.join("")

        }
        else if (yz.isString(msg.toUserId)) {
            //如果是单发
            if (msg.toUserId == "") {
                resolve();
            }
            toUserId = "&toUserId=" + msg.toUserId
        }
        else {
            resolve();
        }




        var params = "content=" + JSON.stringify(content) + "&fromUserId=2191" + toUserId + "&objectName=RC:TxtMsg&pushContent=thisisapush&pushData={\"pushData\":\"hello\"}&count=4&verifyBlacklist=0&isPersisted=1&isCounted=1&isIncludeSender=0"





        superagent.agent()
            .post(BASEURL + "/message/private/publish" + '.' + f)
            .set(HEADERS)
            .send(params)
            .end(function (err, result) {
                console.log(err);
                if (err) {
                    reject(err)
                }
                else {
                    resolve(result)
                }

            });
        // rongcloudSDK.message.private.publish(msg.formUserId, "toUserId=5901ca5f0a408232064bc5f4&toUserId=messager&toUserId=3", "RC:TxtMsg", JSON.stringify(content), msg.pushContent, "", "", function (err, data) {

        //     if (err) {
        //         reject(err)
        //     }
        //     else {
        //         resolve(data)
        //     }



        // })

    })

}






